<template>
  <div class="page">
    <global-header title="申请管理" @back="$router.back()" />
    <main class="page-main !overflow-hidden page">
      <van-dropdown-menu>
        <van-dropdown-item v-model="form.type" :options="updownType" />
        <van-dropdown-item :title="dateRange" ref="itemRef">
          <div class="h-[400px] overflow-y-auto">
            <van-calendar
              ref="calendarRef"
              switch-mode="month"
              :lazy-render="false"
              :min-date="minDate"
              :max-date="maxDate"
              :show-title="false"
              :default-date="form.date"
              :poppable="false"
              type="range"
            >
              <template #footer>
                <div class="grid grid-cols-2 gap-x-[10px] py-[10px]">
                  <van-button size="small" round block @click="onCancel">取消</van-button>
                  <van-button size="small" type="primary" round block @click="onConfirm">
                    确定
                  </van-button>
                </div>
              </template>
            </van-calendar>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>
      <div class="bg-[#fff]">
        <van-search
          class="search-field"
          @search="handleSearch"
          @clear="handleSearch"
          @click-left-icon="handleSearch"
          v-model="form.name"
          placeholder="搜索用户名/昵称/备注"
          shape="round"
        >
          <template #left-icon>
            <div class="flex items-center h-full">
              <svg-icon name="chat-search"></svg-icon>
            </div>
          </template>
        </van-search>
      </div>
      <div class="px-[15px] pb-[10px] bg-[#fff]">
        <custom-tabs v-model:value="form.status" :options="statusType" />
        <div
          class="h-[26px] bg-[#f1f4fb] text-[14px] text-[#888] rounded-full mt-[10px] text-center leading-[26px]"
        >
          {{ formatTime(form.date[0]) }} - {{ formatTime(form.date[1]) }}
        </div>
      </div>
      <div class="px-[15px] py-[10px] bg-[#fff] mt-[10px] border-bottom">
        <div class="flex justify-between items-center text-[14px] text-[#888]">
          <div class="flex-1 w-0">总上分: {{ totalUp }}</div>
          <div class="flex-1 w-0">总下分: {{ totalDown }}</div>
        </div>
      </div>
      <div class="px-[15px] bg-[#fff] py-[10px] border-bottom">
        <ul class="flex justify-between items-center text-[14px]">
          <li class="flex-[1.5] w-0 text-center">类型</li>
          <li class="flex-1 w-0 text-center">时间</li>
          <li class="flex-[1.5] w-0 text-center">积分</li>
          <li class="flex-1 w-0 text-center">状态</li>
        </ul>
      </div>
      <div class="page-main">
        <div class="bg-white">
          <scroll-list
            emptyImage
            enableRefresh
            v-model:loading="state.loading"
            v-model:refresh="state.refresh"
            :finished="state.finished"
            :length="list.length"
            @refresh="refresh"
            @load="load"
          >
            <template v-for="item in list">
              <UpdownItem :item="item" @show="handleShow" @detail="handleDetail" />
            </template>
          </scroll-list>
        </div>
      </div>
    </main>
    <MemberInfoPopup :uid="memberId" ref="memberInfoPopupRef" />
    <UpdownStatusPopup :id="updownId" ref="updownStatusPopupRef" @update="handleUpdate" />
  </div>
</template>
<route>
  {
    name: "admin-apply-updown",
    meta: {
      pageIndex: 3,
    }
  }
</route>
<script setup lang="ts">
import UpdownItem from "./components/updown-item.vue";
import MemberInfoPopup from "./components/member-info-popup.vue";
import UpdownStatusPopup from "./components/updown-status.popup.vue";

import $bus from "@/utils/bus";
import moment from "moment";
import { reqUpdownList } from "@/api/apply";
import { useList } from "@/hooks/useList";
import { formatDate } from "@/utils/common";
import { cloneDeep, debounce } from "lodash-es";
import { usePremsStore } from "@/store/modules/prems";
import { toast } from "@/utils/toast";

interface Params {
  Type?: string;
  Status?: string;
  Name?: string;
  StartDate?: string;
  EndDate?: string;
}

const itemRef = ref();
const calendarRef = ref();
const memberInfoPopupRef = ref();
const updownStatusPopupRef = ref();
const premsStore = usePremsStore();
const statusType = [
  { text: "全部", value: "-1" },
  { text: "审核中", value: "1" },
  { text: "已通过", value: "2" },
  { text: "已驳回", value: "3" }
];
const updownType = [
  { text: "全部申请", value: "-1" },
  { text: "上分申请", value: "1" },
  { text: "下分申请", value: "2" }
];
const form = reactive({
  name: "",
  status: "-1",
  type: "-1",
  date: <Date[]>[moment().toDate(), moment().toDate()]
});
const memberId = ref(0);
const updownId = ref(0);
const minDate = computed(() => moment().subtract(1, "months").toDate());
const maxDate = computed(() => moment().add(1, "days").toDate());
const totalUp = computed(() => {
  const upList = list.value.filter(v => v.Type == 1);
  return upList.reduce((a, b) => a + b.Amount, 0);
});
const totalDown = computed(() => {
  const downList = list.value.filter(v => v.Type == 2);
  return downList.reduce((a, b) => a + b.Amount, 0);
});
const dateRange = computed(() => {
  if (!form.date) return "选择日期";
  return `${moment(form.date[0]).format("YYYY/MM/DD")} - ${moment(form.date[1]).format("MM/DD")}`;
});

const formatTime = (date: Date) => {
  return formatDate(moment(date).format("YYYY/MM/DD"), "YYYY/MM/DD");
};
const onConfirm = () => {
  if (calendarRef.value) {
    const values = calendarRef.value?.getSelectedDate();
    form.date = values.length == 1 ? [values[0], values[0]] : values;
    itemRef.value?.toggle();
  }
};

const onCancel = () => {
  form.date = [moment().toDate(), moment().toDate()];
  itemRef.value?.toggle();
};

const getParams = () => {
  const params: Params = {};

  if (form.type && form.type != "-1") {
    params.Type = form.type;
  }
  if (form.status && form.status != "-1") {
    params.Status = form.status;
  }
  if (form.name) {
    params.Name = form.name;
  }
  if (form.date) {
    params.StartDate = moment(form.date[0]).format("YYYY-MM-DD 00:00:00");
    params.EndDate = moment(form.date[1]).format("YYYY-MM-DD 23:59:59");
  }
  return params;
};

const { state, list, getData, load, search, refresh } = useList<UpdownItemMo, any>(
  reqUpdownList,
  getParams
);

const handleSearch = debounce(() => {
  search();
}, 500);

const handleShow = (id: number) => {
  if (!premsStore.isApplyUpdown) {
    toast.info("暂无权限");
    return;
  }
  updownId.value = id;
  nextTick(() => {
    updownStatusPopupRef.value?.open();
  });
};

const handleDetail = (id: number) => {
  memberId.value = id;
  nextTick(() => {
    memberInfoPopupRef.value?.open();
  });
};

const handleUpdate = (id: number, flag: boolean) => {
  const arr = cloneDeep(list.value);
  arr.forEach(jtem => {
    if (jtem.Id == id) {
      jtem.Status = flag ? 2 : 3;
    }
  });
  list.value = cloneDeep(arr);
};
watch(
  () => [form.date, form.status, form.type],
  () => {
    nextTick(search);
  }
);
onMounted(() => {
  getData();
  // 监听更新上下分消息
  $bus.on("update-updown-msg", () => {
    nextTick(search);
  });
});
onBeforeUnmount(() => {
  $bus.off("update-updown-msg");
});
</script>
<style scoped lang="scss">
:deep() {
  .van-dropdown-menu {
    --van-dropdown-menu-height: 30px;
    .van-dropdown-menu__bar {
      padding: 6px 0;
      box-shadow: none;
      .van-dropdown-menu__item:first-child {
        border-right: 1px solid #e4e4e4;
      }
    }
    .van-dropdown-item__content {
      border-top: 1px solid #e4e4e4;
    }
  }
  // .van-calendar__header-title {
  //   display: none;
  // }
}
</style>
